﻿#include <unordered_map>
#include <vector>
using namespace std;

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> prefixSumCount;
        prefixSumCount[0] = 1;

        int currentSum = 0;
        int result = 0;

        for (int num : nums) {
            currentSum += num;

            if (prefixSumCount.find(currentSum - k) != prefixSumCount.end()) {
                result += prefixSumCount[currentSum - k];
            }

            prefixSumCount[currentSum]++;
        }

        return result;
    }
};
int main() {
    // 创建解决方案实例
    Solution solution;

    // 测试用例1
    vector<int> nums1 = { 1, 1, 1 };
    int k1 = 2;
    cout << "测试用例1: 数组 = [1, 1, 1], k = 2" << endl;
    cout << "和为" << k1 << "的子数组个数: " << solution.subarraySum(nums1, k1) << endl;  

    // 测试用例2
    vector<int> nums2 = { 1, 2, 3 };
    int k2 = 3;
    cout << "\n测试用例2: 数组 = [1, 2, 3], k = 3" << endl;
    cout << "和为" << k2 << "的子数组个数: " << solution.subarraySum(nums2, k2) << endl; 

    // 测试用例3
    vector<int> nums3 = { 1, -1, 0 };
    int k3 = 0;
    cout << "\n测试用例3: 数组 = [1, -1, 0], k = 0" << endl;
    cout << "和为" << k3 << "的子数组个数: " << solution.subarraySum(nums3, k3) << endl;  
    return 0;
}
